<template>
  <div class="ai-chat-input">
    <textarea
      ref="textarea"
      v-model="content"
      :placeholder="placeholder"
      :disabled="disabled"
      :style="{ height: textareaHeight }"
      @input="handleInput"
      @paste="handlePaste"
      @keydown="handleKeydown"
    />
    <!-- 上传进度提示 -->
    <div v-if="uploading" class="upload-indicator">
      <i class="el-icon-loading" />
      <span>图片上传中...</span>
    </div>
  </div>
</template>

<script>
import { Post as UploadBase64Image } from '@/api/cms/image'

export default {
  name: 'AIChatInput',
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '输入消息...'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    minHeight: {
      type: Number,
      default: 120
    },
    maxHeight: {
      type: Number,
      default: 400
    },
    autoHeight: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      content: this.value,
      textareaHeight: `${this.minHeight}px`,
      uploading: false
    }
  },
  watch: {
    value(val) {
      if (val !== this.content) {
        this.content = val
        this.$nextTick(() => {
          this.adjustHeight()
        })
      }
    },
    content(val) {
      this.$emit('input', val)
    }
  },
  mounted() {
    this.adjustHeight()
  },
  methods: {
    // 处理输入事件
    handleInput() {
      if (this.autoHeight) {
        this.adjustHeight()
      }
    },

    // 自动调整高度
    adjustHeight() {
      if (!this.autoHeight || !this.$refs.textarea) return

      const textarea = this.$refs.textarea

      // 重置高度以获取正确的 scrollHeight
      textarea.style.height = 'auto'

      // 计算新高度
      const scrollHeight = textarea.scrollHeight
      let newHeight = Math.max(this.minHeight, scrollHeight)

      // 限制最大高度
      if (this.maxHeight && newHeight > this.maxHeight) {
        newHeight = this.maxHeight
        textarea.style.overflowY = 'auto'
      } else {
        textarea.style.overflowY = 'hidden'
      }

      this.textareaHeight = `${newHeight}px`
    },

    // 处理键盘事件
    handleKeydown(event) {
      // Ctrl+Enter 或 Cmd+Enter 发送消息
      if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
        event.preventDefault()
        this.$emit('send')
      }
    },

    // 处理粘贴事件
    async handlePaste(event) {
      const items = Array.from(event.clipboardData.items)
      const imageItems = items.filter(item => item.type.startsWith('image/'))

      if (imageItems.length === 0) return

      // 阻止默认粘贴行为（防止图片作为 base64 插入）
      event.preventDefault()

      // 处理每个图片
      for (const item of imageItems) {
        await this.handleImageUpload(item)
      }
    },

    // 处理图片上传
    async handleImageUpload(item) {
      const file = item.getAsFile()
      if (!file) return

      this.uploading = true

      try {
        // 转换为 base64
        const base64Data = await this.fileToBase64(file)

        // 调用上传接口
        const response = await UploadBase64Image({
          file_data: base64Data,
          directory_id: -1,
          keyword: ''
        })

        // 触发图片上传成功事件
        this.$emit('image-uploaded', {
          url: response.data.url,
          size: file.size,
          name: file.name,
          type: file.type
        })

        this.$message.success('图片上传成功')
      } catch (error) {
        console.error('图片上传失败:', error)
        this.$message.error('图片上传失败: ' + (error.message || '未知错误'))
      } finally {
        this.uploading = false
      }
    },

    // 将文件转换为 base64
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = () => {
          resolve(reader.result)
        }
        reader.onerror = (error) => {
          reject(error)
        }
        reader.readAsDataURL(file)
      })
    },

    // 获取内容（纯文本）
    getContent() {
      return this.content
    },

    // 设置内容
    setContent(content) {
      this.content = content
      this.$nextTick(() => {
        this.adjustHeight()
      })
    },

    // 清空内容
    clearContent() {
      this.content = ''
      this.textareaHeight = `${this.minHeight}px`
    },

    // 聚焦输入框
    focus() {
      this.$refs.textarea?.focus()
    },

    // 失焦
    blur() {
      this.$refs.textarea?.blur()
    }
  }
}
</script>

<style lang="scss" scoped>
.ai-chat-input {
  position: relative;
  width: 100%;

  textarea {
    width: 100%;
    padding: 12px;
    font-size: 14px;
    line-height: 1.6;
    color: #303133;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #fff;
    resize: none;
    outline: none;
    transition: border-color 0.2s;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;

    &::placeholder {
      color: #c0c4cc;
    }

    &:focus {
      border-color: #409eff;
    }

    &:disabled {
      background-color: #f5f7fa;
      border-color: #e4e7ed;
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }

  .upload-indicator {
    position: absolute;
    bottom: 8px;
    right: 12px;
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 4px 8px;
    background: rgba(64, 158, 255, 0.1);
    border-radius: 4px;
    font-size: 12px;
    color: #409eff;
    pointer-events: none;

    i {
      font-size: 14px;
    }
  }
}
</style>
